<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随机颜色</title>
    <style>
        div {
            width: 300px;
            height: 300px;
            background: lightcyan;
        }
    </style>
</head>

<body>
    <div>随机切换颜色</div>
    <button>切换</button>
    <button>停止</button>
    <script>
        //    获取dom
        var oDiv = document.querySelector("div");
        var aBtn = document.querySelectorAll("button");
        var timer = null;
        // 点击切换颜色
        aBtn[0].onclick = function () {
            oDiv.style.background = getRandomColor();
        }

        // 在不点击的时候每隔两秒切换颜色
        timer = setInterval(function () {
            oDiv.style.background = getRandomColor();
        }, 2000);

        // 停止定时器
        aBtn[1].onclick = function () {
            clearInterval(timer);
        };


        // 随机颜色
        function getRandomColor() {
            var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
            //2.创建一个字符串
            var str = "#";
            //3.写循环 ,随机获取6位颜色值
            for (var i = 0; i < 6; i++) {
                str += arr[getRandom(0, arr.length - 1)];
            }
            return str;
        }

        function getRandom(min, max) {
            return Math.floor(Math.random() * (max - min + 1) + min);
        }

    </script>
</body>

</html>